<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:page="page"
               v-model:search="search"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @sort-change="sortChange"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               :summary-method="summaryMethod"
               @refresh-change="refreshChange">
      <template  #menu-left>
        <el-button type="warning" icon="el-icon-download"  @click="handleExport">导 出
        </el-button>
        <el-button
                type="success"
                icon="Check"
                @click="handleCheck"
                v-if="permission.bill_check_audit"
        >过账
        </el-button>
        <el-button
                type="danger"
                icon="Close"
                @click="handleUnCheck"
                v-if="permission.bill_check_reject"
        >反过账
        </el-button>
      </template>

      <template #customerNo-search="{ disabled, size }">
        <el-autocomplete
                style="width: 100%;"
                v-model="search.customerNo"
                :fetch-suggestions="queryCustomerNo"
                placeholder="请输入客户账号"
                :trigger-on-focus="false"
                @select="selectCustomerNo"
                :fit-input-width="true"
        ></el-autocomplete>
      </template>
      <template #customerName-search>
        <el-input v-model="search.customerName" readonly placeholder="请选择客户名称" @click="selectCustomerName" />
      </template>
      <template #factoryName-search>
        <el-input v-model="search.factoryName" readonly placeholder="请选择工厂信息" @click="selectFactory"/>
      </template>
      <template #outDate-search="{ disabled, size }">
        <!--<div style="display: flex;flex-direction: start;">-->
        <!--<el-select v-model="query.stockDateRule" placeholder="比较" filterable clearable>-->
        <!--<el-option label="" value=""></el-option>-->
        <!--<el-option value=">" label="大于">大于</el-option>-->
        <!--<el-option value=">=" label="大于等于">大于等于</el-option>-->
        <!--<el-option value="=" label="等于">等于</el-option>-->
        <!--<el-option value="!=" label="不等于">不等于</el-option>-->
        <!--<el-option value="<=" label="小于等于">小于等于</el-option>-->
        <!--<el-option value="<" label="小于">小于</el-option>-->
        <!--</el-select>-->
        <!--<el-date-picker-->
        <!--size="default"-->
        <!--v-model="query.stockDateSearch"-->
        <!--type="date"-->
        <!--:format="dateFormat"-->
        <!--:value-format="dateFormat"-->
        <!--:unlink-panels="true"-->
        <!--clearable-->
        <!--placeholder="入仓日期"-->
        <!--:picker-options="pickerOptions"-->
        <!--&gt;-->
        <!--</el-date-picker>-->
        <!--</div>-->
        <el-date-picker
                size="default"
                style="width:94%"
                v-model="this.stockDateRange"
                type="daterange"
                :format="dateFormat"
                :value-format="dateFormat"
                unlink-panels
                start-placeholder="Start Date"
                end-placeholder="End Date"
                clearable
                placeholder="送货日期"
                @change="handleStockDateChange"
                :picker-options="pickerOptions"
        >
        </el-date-picker>
      </template>
    </avue-crud>
    <select-customer  ref="selectCustomer"  @success="setCustomerNo"/>
    <select-factory  ref="selectFactory"  @success="setFactory"/>
    <select-bank  ref="selectBank"  @success="setBank"/>
  </basic-container>
</template>

<script>
  import {listCustBillCheck} from "@/api/anwise/stock/stock_out_item";
  import {changeBillStatus} from "@/api/anwise/stock/stock_out_main";
  import {remoteList} from '@/api/anwise/customer/customer';
  import {mapGetters} from "vuex";
  import selectCustomer from '../order/components/select_customer.vue';
  import selectFactory from '../order/components/select_factory.vue';
  import {Pattern} from "@/utils/validate.js";
  import { getToken } from '@/utils/auth';
  import { exportBlobPost ,exportBlob} from '@/api/common';
  import { downloadXls } from '@/utils/util';
  import NProgress from 'nprogress';
  import 'nprogress/nprogress.css';

  export default {
      components: {
          selectCustomer,
          selectFactory
      },
    data() {
      return {
          isEnglish:'1',
          hiddenPrice:'1',
          selectId:'',
          box:false,
          form: {},
          query: {},
          stockDateRange:[],
          loading: false,
          dateFormat: 'YYYY-MM-DD',
          pickerOptions: {},
          page: {
              pageSize: 20,
              currentPage: 1,
              total: 0
          },
          search:{},
          selectionList: [],
          option: {
              height:'auto',
              calcHeight: 30,
              tip: false,
              searchShow: true,
              searchMenuSpan: 6,
              border: true,
              index: true,
              // selection: true,
              reserveSelection:true,
              labelWidth: 150,
              indexWidth:100,
              menuWidth: 230,
              addBtn: false,
              editBtn: false,
              viewBtn: false,
              delBtn: false,
              stripe: true,
              searchIndex: 3,
              searchIcon: false,
            searchEnter:true,
              menu:false,
              showSummary: true,
              // selectable:(row,index)=>{
            //   return row.orderStatus =='open';
            // },
          column: [

              {
                  label: "客户账号",
                  prop: "customerNo",
                  type: "input",
                  search: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  hide:true,
                  rules: [{
                      required: true,
                      message: "请输入客户账号",
                      trigger: "blur"
                  }],
              },
              {
                  label: "客户名称",
                  prop: "customerName",
                  type: "input",
                  search: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  hide:true,
                  rules: [{
                      required: true,
                      message: "请输入客户名称",
                      trigger: "blur"
                  }],
              },
              {
                  label: "工厂名称",
                  prop: "factoryName",
                  type: "input",
                  search:true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  hide:true,
              },
              {
                  label: "送货日期",
                  prop: "outDate",
                  type: "input",
                  search:true,
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
            {
              label: "送货单号",
              prop: "idNo",
              type: "input",
                fixed: true,
                overHidden: true,
                sortable: true,
                width:120,
              rules: [{
                required: true,
                message: "请输入送货单号",
                trigger: "blur"
              }],
            },
            {
              label: "出仓项",
              prop: "itemNo",
              type: "input",
              fixed: true,
              overHidden: true,
              sortable: true,
              width:120,
              rules: [{
                required: true,
                message: "请输入出仓项",
                trigger: "blur"
              }],
            },
              {
                  label: "订货日期",
                  prop: "salesDate",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入订单日期",
                      trigger: "blur"
                  }],
              },
              {
                  label: "订单号码",
                  prop: "orderNo",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入订单号码",
                      trigger: "blur"
                  }],
              },
              {
                  label: "订单项",
                  prop: "orderItem",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入订单项",
                      trigger: "blur"
                  }],
              },
              {
                  label: "是否已对账",
                  prop: "billCheck",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:140,
              },
              {
                  label: "客户PO#",
                  prop: "custPo",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入客户PO",
                      trigger: "blur"
                  }],
              },
              {
                  label: "客户条码",
                  prop: "barCode",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入客户条码",
                      trigger: "blur"
                  }],
              },
              {
                  label: "送货数量",
                  prop: "num",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
                  formatter:(val,value,label)=>{
                      return this.currencyFilter(value);
                  },
                  rules: [{
                      required: true,
                      message: "请输入送货数量",
                      trigger: "blur"
                  }],
              },
              {
                  label: "单价/100PCS",
                  prop: "orderItemPrice",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:140,
                  rules: [{
                      required: true,
                      message: "请输入单价/100PCS",
                      trigger: "blur"
                  }],
              },
            {
              label: "金额",
              prop: "outAmount",
              type: "input",
              overHidden: true,
              sortable: true,
              width:120,
              formatter:(val,value,label)=>{
                return this.currencyFilter(value);
              },
              rules: [{
                required: true,
                message: "请输入金额",
                trigger: "blur"
              }],
            },
            {
              label: "运费分摊",
              prop: "freightPrice",
              type: "input",
              overHidden: true,
              sortable: true,
              width:180,
              formatter:(val,value,label)=>{
                return this.currencyFilter(value);
              },

            },
            {
              label: "合计",
              prop: "totalAmount",
              type: "input",
              overHidden: true,
              sortable: true,
              width:180,
              formatter:(val,value,label)=>{
                return this.currencyFilter(value);
              },

            },
              {
                  label: "出仓币别",
                  prop: "orderRmb",
                  type: "select",
                  filterable: true,
                  overHidden: true,
                  sortable: true,
                  width:120,
                  dicUrl: '/api/blade-system/dict-biz/dictionary?code=rmb',
                  props: {
                      label: 'dictValue',
                      value: 'dictKey',
                  },
                  dataType: 'string',
                  rules: [{
                      required: false,
                      message: "请输入出仓币别",
                      trigger: "blur"
                  }],
              },
              {
                  label: "客户联系人",
                  prop: "contact",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:140,
                  rules: [{
                      required: true,
                      message: "请输入客户联系人",
                      trigger: "blur"
                  }],
              },
              {
                  label: "业务人员",
                  prop: "serviceName",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入业务人员",
                      trigger: "blur"
                  }],
              },
              {
                  label: "出仓备注",
                  prop: "remark",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入出仓备注",
                      trigger: "blur"
                  }],
              },
              {
                  label: "收货工厂",
                  prop: "factoryName",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
                  rules: [{
                      required: true,
                      message: "请输入收货工厂",
                      trigger: "blur"
                  }],
              }
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.order_add, false),
          viewBtn: this.validData(this.permission.order_view, false),
          delBtn: this.validData(this.permission.order_delete, false),
          editBtn: this.validData(this.permission.order_edit, false)
        };
      },

    },
    methods: {
        summaryMethod ({ columns, data }) {
            const sums = [];
            if (columns.length > 0) {
                sums[0] = '合计：';
                columns.forEach((column, index) => {
                    let prop = column.property
                    if (['num','outAmount','freightPrice','totalAmount'].includes(prop)) {
                        let values = this.data.map(item => Number(item[prop] || 0));
                        let all = values.length !== 0 ? sums[index] = values.reduce((a, b) => {
                            return a + b;
                        }) : 0
                        if (prop == 'num' ) {
                            sums[index] = this.currencyFilter(all.toFixed(0));
                        } else  {
                            sums[index] = this.currencyFilter(this.$toFixed(all,2));
                        }
                    }
                });
            }
            return sums;
        },
        handleCheck() {
            if (!this.query.outDateStart || !this.query.outDateEnd || !this.query.customerId) {
                this.loading = false;
                this.$message({
                    type: "error",
                    message: "请选择客户/送货日期！"
                });
                return;
            }
            changeBillStatus(this.query,1).then(res=> {
                if (res.data.success) {
                    this.$message({
                        type: "success",
                        message: res.data.msg || "对账成功！"
                    });
                    this.onLoad(this.page);
                }else {
                    this.$message({
                        type: "error",
                        message: res.data.msg
                    });
                }
            })
        },
        handleUnCheck() {
            if (!this.query.outDateStart || !this.query.outDateEnd || !this.query.customerId ) {
                this.loading = false;
                this.$message({
                    type: "error",
                    message: "请选择客户/送货日期！"
                });
                return;
            }
            changeBillStatus(this.query,0).then(res=> {
                if (res.data.success) {
                    this.$message({
                        type: "success",
                        message: res.data.msg || "反对账成功！"
                    });
                    this.onLoad(this.page);
                }else {
                    this.$message({
                        type: "error",
                        message: res.data.msg
                    });
                }
            })
        },
        handleExport() {
            if (!this.query.outDateStart || !this.query.outDateEnd || !this.query.customerId ) {
                this.loading = false;
                this.$message({
                    type: "error",
                    message: "请选择客户/送货日期！"
                });
                return;
            }
          this.query.toNo = this.query.customerNo;
          this.query.toName = this.query.customerName;
          NProgress.start();
          exportBlob(
                  `/blade-anwise/stock/stock_out_main/custBillCheckExport?${this.website.tokenHeader
                  }=${getToken()}`, this.query
          ).then(res => {
            downloadXls(res.data, this.query.customerName+`对账单${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
            NProgress.done();
          });
        },
        mounted() {
            this.loading = false;
        },
        setFactory(row) {
            if (row) {
                this.search.factoryId = row.id;
                this.search.factoryName = row.facName;
            }
        },
        selectFactory() {
            if (this.search.customerNo)  {
                this.$refs.selectFactory.showSelect(this.search.customerId);
            } else {
                this.$message({
                    type: "error",
                    message: "请先选择客户信息!"
                });
            }
        },
        setCustomerNo(row) {
            this.search.customerName = "";
            if (row) {
                this.search.customerId = row.id;
                this.search.customerNo = row.custNo;
                this.search.customerName = row.custName;}
        },
        selectCustomerName() {
            this.$refs.selectCustomer.showSelect();
        },

        queryCustomerNo(val,cb) {
            this.search.customerName = "";
            this.search.factoryName = "";
            const reg = Pattern.number;
            console.log(reg.test(val));
            if (!reg.test(val)) {
                this.$message({
                    type: "error",
                    message: "客户账号只能为数字!"
                });
                return;
            }

            remoteList(val).then(res => {
                if (res.data.success) {
                    let customerList = [];
                    res.data.data.forEach(item => {
                        customerList.push({
                            value:item.custNo +" - "+item.custName,
                            customerId: item.id,
                            customerNo: item.custNo,
                            customerName: item.custName,
                        });
                    })
                    cb(customerList);
                }
            })
        },
        selectCustomerNo(item) {
            console.log(item);
            this.search.customerId = item.customerId;
            this.search.customerNo = item.customerNo;
            this.search.customerName = item.customerName;
        },
        orderReport(id) {
            orderReport(this.selectId, this.isEnglish, this.hiddenPrice).then(res => {
                if(res.data.success) {
                    console.log(res.data)
                    const file = res.data.data;
                    // const originUrl = (file.url.replace(file.domain, `${this.res}/`));
                    const url = file.url;
                    // this.$refs.preview.open({
                    //     url: url || "",
                    //     originUrl: originUrl || ""
                    // });
                    window.open(`/plugins/pdfjs/web/viewer.html?file=`+url);
                }
            })
        },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
        sortChange(val) {
            console.log(val)
            this.sort = {
                prop: val.prop,
                order: val.order
            };
            let order = "";
            if (this.sort.prop && this.sort.order) {
                if (this.sort.order === "descending") {
                    order = `${this.sort.prop} desc`
                } else {
                    order = `${this.sort.prop} asc`
                }
            }
            this.query.orderBy = order;
            this.onLoad(this.page);
        },
      searchReset() {
        this.query = {};
          this.search.customerId = "";
          this.search.customerNo = "";
          this.search.customerName = "";
          this.search.factoryId = "";
          this.search.factoryName = "";
          this.stockDateRange = [];
          this.search.outDateStart = '';
          this.search.outDateEnd = '';
          this.data=[];
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
          this.onLoad(this.page);
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
          this.onLoad(this.page);
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
            console.log(params);
          let filter = Object.assign(params, this.query);
          if (!filter.customerId  || !filter.outDateStart || !filter.outDateEnd) {
                this.$message({
                    type: "error",
                    message: "请选择客户/送货日期！!"
                });
                return;
            }
          filter.toNo = filter.customerNo;
        this.loading = true;
        listCustBillCheck(page.currentPage, page.pageSize, filter).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
        handleStockDateChange(value) {
            if (value) {
                this.search.outDateStart = value[0];
                this.search.outDateEnd = value[1];
            } else {
                this.search.outDateStart = '';
                this.search.outDateEnd = '';
            }
        }
    }
  };
</script>

<style>

  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button{
    -webkit-appearance: none !important;
    margin: 0;
  }
</style>
